package com.bsoft.gol.editor.service.impl;

import com.alibaba.fastjson.JSONObject;

import ctd.util.annotation.RpcService;
import com.bsoft.gol.editor.editor.ImportLog;
import com.bsoft.gol.editor.fileUpload.*;
import com.bsoft.gol.editor.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.bsoft.gol.editor.service.ExcelDataImportService;
import com.bsoft.gol.editor.service.ImportLogService;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Date;


/**
 * @author sangshuang
 */
@Service("defaultExeclDataImportService")
public class DefaultExeclDataImportService implements ExcelDataImportService {

    private final static Logger logger = LoggerFactory.getLogger(DefaultExeclDataImportService.class);
	private ExcelDataWriter excelDataWriter = new DefaultExcelDataWriter();

	@Autowired
	private UserDataTranslator userDataTranslator;
    @Autowired
	private ImportLogService importLogService;
    @Autowired
	private DataUpdateHandler<UserHolder> userHolder;



	/**
	 * 根据数据导入日志的记录ID，将其写入的excel中，然后生成流,并更新日志记录状态
	 * @param logId 日志ID
	 * @param failJson 未导入的数据JSON字符串
	 * @return excel的文件流
	 */
	@Override
	@RpcService
	public byte[] writeExcel(int logId,String dataType){
		if(logId == 0){
			byte[] result = excelDataWriter.write(logId, dataType, null);
			return result;
		}
		ImportLog log = importLogService.getLogById(logId);
		if(log != null){
			byte[] result = excelDataWriter.write(logId, log.getDataType(), log.getFailJson());
			log.setId(logId);
			log.setDownloadDate(new Date());
			try {
				importLogService.updateImportLogDownloadInfo(log);
				return result;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public ImportResult importData(ImportVo importVo){
		String dataType = importVo.getDataType();
		long start = System.currentTimeMillis();
		ImportResult result = null;
		//导入用户数据
		if(UploadFieldNameEnum.DATA_USER_DISEASE.value.equals(dataType)){
			logger.info("基础数据导入用户数据:.....");
        	result = importOrgData(importVo);
    	}
		if(result != null){
			Date date = new Date();
			ImportLog log = result.getLog();
			log.setDataType(dataType);
			log.setFail(result.getFailCount());
			log.setTotal(result.getTotal());
			log.setSuccess(result.getSuccesCount());
			log.setFileName(importVo.getFileName());
			log.setTakeMs(date.getTime() - start);
			log.setCreatedDate(date);
			log = importLogService.saveImportLog(log);
		}
		logger.info("基础数据导入数据:结束");
		return result;
	}
	

	private ImportResult importOrgData(ImportVo importVo){
		ImportLog log = new ImportLog();
		ImportResult importResult = null;
		try {
			//读取
			ExcelDataReader<UserInExcel> reader = UserDataReader.getReader();
			reader.initFields();
			TableData<UserInExcel> tableDataInExcel = reader.read(new ByteArrayInputStream(importVo.getData()),importVo.getFileName());
			//转换+校验
			TableData<UserHolder> tableDataHolder = userDataTranslator.translate(tableDataInExcel);
			//保存更新删除
			userHolder.saveData(tableDataHolder);
			//转换返回-保存日志
			importResult = userDataTranslator.reverse(tableDataHolder,tableDataInExcel);
			//实例化导入服务的日志
			log.setImportMsg(tableDataInExcel.getInvalidMsg().length() > 0 ? tableDataInExcel.getInvalidMsg().substring(1) :"");
			log.setFailJson(JSONObject.toJSONString(tableDataInExcel));
		} catch (Exception e) {
			e.printStackTrace();
			if(importResult == null){
				importResult = new ImportResult();
			}
			log.setImportMsg("导入过程发生异常:" + ExecptionStackUtil.getStackError(e));
		}
		importResult.setLog(log);
		return importResult;
	}

}
